// controllers/taskController.js
const task = require('../models/task');

function getTasks(req, res) {
    const { userId } = req.query;
    task.getTasksByUserId(userId)
        .then(tasks => {
            res.status(200).json(tasks);
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

function addTask(req, res) {
    const { text, userId } = req.body;
    const taskId = Date.now(); // Simple task ID generation
    task.addTask(taskId, text, userId)
        .then(taskId => {
            res.status(201).send({ message: 'Task added', taskId });
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

function updateTask(req, res) {
    const { id } = req.params;
    const { text, completed } = req.body;
    task.updateTask(id, text, completed)
        .then(changes => {
            if (changes) {
                res.status(200).send({ message: 'Task updated' });
            } else {
                res.status(404).send({ message: 'Task not found' });
            }
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

function deleteTask(req, res) {
    const { id } = req.params;
    task.deleteTask(id)
        .then(changes => {
            if (changes) {
                res.status(200).send({ message: 'Task deleted' });
            } else {
                res.status(404).send({ message: 'Task not found' });
            }
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

module.exports = {
    getTasks,
    addTask,
    updateTask,
    deleteTask
};